# -*- coding: utf-8 -*-

from rest_framework import  serializers
from books.models import BookInfo
class HeroInfoSerialzier(serializers.Serializer):
    # 英雄序列化器
    hname = serializers.CharField()
    hcomment = serializers.CharField()
    hbook = serializers.PrimaryKeyRelatedField(read_only=True)
    # hbook=serializers.PrimaryKeyRelatedField()
    #hbook = serializers.StringRelatedField(label='图书')

class BookSerialzier(serializers.Serializer):
    #反序列化验证的时候，可以加参数 限定请求的参数
    btitle  = serializers.CharField(label='书名',max_length=20,min_length=2)

    bpub_date=serializers.DateField()#默认是需要传递的参数
    bread = serializers.IntegerField(max_value=100,min_value=1)
    bcomment= serializers.IntegerField(default=10)
#hc = serializers.StringRelatedField(label='英雄')
    # heroinfo_set = serializers.StringRelatedField(read_only=True, many=True)
    # heroinfo_set2 = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
   # heroinfo_set = HeroInfoSerialzier(many=True)



    #"   单一字段验证,方法名不能随意指定]""
    def validate_btitle(self,value):
       if value == 'python':
           raise serializers.ValidationError('书名不能是python')
       return  value
   #多个字段验证
    # def validate(self,data):
    #     if data['bread']>data['bcoment']:
    #         raise serializers.ValidationError('阅读量错误')
    #     return data

    #保存数据
    def create(self, validated_data):
        book=  BookInfo.objects.create(**validated_data)
        return book


    #数据更新 put 请求
    def update(self, instance, validated_data):
        #instance接受传递过来的数据对象
        instance.btitle = validated_data['btitle']
        instance.bread= validated_data['bread']
        instance.save()
        return instance

class BookModelSerialzier(serializers.ModelSerializer):

    #显示指明字段,初始化字段时的值
    bread= serializers.IntegerField(min_value=1)

    #可增加验证字段
    sms_code = serializers.CharField(max_length=6,min_length=2)

    #添加字段选项参数
    # read_only_fields=('btitle')
    class Meta:
        model = BookInfo#指定生成字段的模型类
        # fields =('btitle','bread')#指定模型类中的字段
        # fields= '__all__'#生成模型类中的所有字段

        exclude=('btitle',)#除了这个字段之外的 都生成
        extra_kwargs={
            'bcomment':{
                'max_value':100,
                'min_value':1,
            }

        }





